package com.woniuxy.service.impl;

import com.woniuxy.dao.StudentDao;
import com.woniuxy.dao.impl.StudentDaoImpl;
import com.woniuxy.entity.Student;
import com.woniuxy.exception.EmailExitesException;
import com.woniuxy.exception.UserNameExistsException;
import com.woniuxy.service.StudentService;

import java.util.List;

/**
 * @author 作者
 * @create 2025-09-17 14:12
 */
public class StudentServiceImpl implements StudentService {

    StudentDao studentDao = new StudentDaoImpl();

    @Override
    public void regist(Student student) {
        //用户名被使用了，不能注册，调用Dao
        Student findStudent = studentDao.selectBySname(student.getSname());
        if (findStudent != null) {
            //用户名已经存在
            throw new UserNameExistsException("用户名已被注册");
        }
        //判断邮箱是否被使用
        findStudent = studentDao.selectByEmail(student.getEmail());
        if (findStudent != null) {
            throw new EmailExitesException("邮箱已被注册");
        }
        studentDao.insert(student);
    }

    @Override
    public Student login(String uname, String password) {
        Student student = studentDao.selectBySname(uname);
        if (student == null) {
            throw new RuntimeException("用户名不存在");
        }
        if (!student.getPassword().equals(password)) {
            throw new RuntimeException("密码错误");
        }
        return student;
    }

    @Override
    public List<Student> getAll() {
        return studentDao.selectAll();
    }

    @Override
    public void removeBySid(int sid) {
        if (studentDao.selectBySid(sid) == null) {
            throw new RuntimeException("要删除的学生不存在");
        } else {
            //        查询所有学生,返回List<Student>
//                从集合中删除学生
//        将这个集合数据重写写入文件,不能append，覆盖
            List<Student> students = studentDao.selectAll();
            for(int i=0;i<students.size();i++){
                if(students.get(i).getSid()==sid){
                    students.remove(i);
                    break;
                }
            }
            studentDao.insertAll(students);
        }
    }
}
